/**
 * Created by dmsoft on 2016/5/4.
 */
define(['jquery', 'domReady!', 'appConst', 'appLocalStorage', 'model/global', 'appMessageBox', 'model/group', 'jquery-form/jquery-form.min'], function ($, domReady, appConst, appLocalStorage, global, msgBox, groupM) {

    var components = {};
    var data = {
        searchFields: {},
        search_key: appConst.searchKey.search_group_key + global.getUserId()
    };
    var that;
    return {
        init: function () {
            that = this;
            components = {
                fm_groupCreate: $("#fm_groupCreate"),
                txt_group_name: $("#txt_group_name"),
                txt_group_desc: $("#txt_group_desc")
            };
            that.initCreateForm();
        },
        initCreateForm: function () {
            components.fm_groupCreate.validate({
                rules: {
                    name: {
                        required: true,
                        nameCheck: true,
                        remote: {
                            type: "POST",
                            url: "group/isExistGroupName",
                            dataType: 'json',
                            data: {
                                groupName: function () {
                                    return components.txt_group_name.val();
                                }
                            }
                        }
                    }
                },
                messages: {
                    name: {
                        required: $.i18n.prop('VALIDATE_REQUIRED', $.i18n.prop('GROUP_NAME')),
                        remote: $.i18n.prop("EXCEPTION_GLOBAL_OBJECT_ALREADY_EXISTS", $.i18n.prop('GROUP_NAME'))
                    }
                },
                submitHandler: function (form) {
                    var searchParam = {
                        'name': components.txt_group_name.val(),
                        'description': components.txt_group_desc.val()
                    };
                    groupM.createGroup(searchParam, function (d) {
                        data.searchFields.search_LIKE_name = components.txt_group_name.val();
                        appLocalStorage.setLocal(data.search_key, JSON.stringify(data.searchFields));
                        window.location.href = "#group";
                    });
                },
                errorPlacement: function (error, element) {
                    error.insertAfter(element.parent());
                }
            });
        }
    }
});